﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
using TeenyGrab.Interfaces;
using TeenyGrab.Objects;
using TeenyGrab.Windows;
using TeenyGrab.Helpers;
using TeenyGrab.Serialization;

namespace TeenyGrab.Outputs
{
    [Serializable]
    public class FtpOutput : IOutput
    {
        public string TmpFilePath { get; set; }
        public string FtpUrl { get; set; }
        public string HttpUrl { get; set; }
        public string User { get; set; }
        public string Pass { get; set; }
        public SerializableImageFormat Format { get; set; }

        public bool Configurable { get { return true; } set { } }

        public string Name { get { return "FTP"; } set { } }

        public string Description { get { return "Uploads image to FTP server."; } set { } }


        public FtpOutput()
        {
            TmpFilePath = "";
            FtpUrl = "ftp://";
            HttpUrl = "http://";
            User = "anonymous";
            Pass = "";
            Format = new SerializableImageFormat(ImageFormat.Jpeg);
        }

        private string GetDateAsFileName()
        {
            var date = DateTime.Now;
            return date.ToString("yyyy-MM-dd_HH-mm-ss");
        }

        public void Configure()
        {
            var configure = new ConfigureFtpOutputWindow(this);
            configure.ShowDialog();
        }

        public void Put(ImageObject image)
        {
            var extension = Format.Format.GetExtension();
            var fname = GetDateAsFileName() + "." + extension;
            image.Image.Save(TmpFilePath + fname, Format.Format);
            
            var request = (FtpWebRequest)WebRequest.Create(FtpUrl+fname);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(User, Pass);

            byte[] fileContents = File.ReadAllBytes(TmpFilePath + fname);
            request.ContentLength = fileContents.Length;

            var requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Flush();
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            System.Windows.Clipboard.SetText(HttpUrl + fname);
            
            var outputWindow = new UrlOutputWindow(HttpUrl + fname);
            outputWindow.ShowDialog();

            response.Close();
        }
    }
}
